import Vue from 'vue'

import md5 from 'blueimp-md5'
import store from '../vuex/storage'

/*
 success回调规范：
 接口处理成功 { code: 1, msg: xxxx, data: xxxx }
 接口处理失败 { code: 0, msg: xxxx }
 接口校验失败 { code: -1, msg: xxxx }
*/
export default function() {
  Vue.prototype.request = function(url, param = {}, loading = true, timeout = 50000000) {
    if (url !== '/login' && !store.state.user) {
      this.$f7.views.main.router.navigate('/login', { reloadAll: true })
      return new Promise((resolve, reject) => {})
    }
    return new Promise((resolve, reject) => {
      const timestamp = Date.now()
      this.$request({
        url: window.baseUrl + url,
        method: 'POST',
        dataType: 'json',
        data: { ...param, timestamp },
        timeout,
        headers: {
          authcode: md5(`${timestamp}tpgj`)
        },
        beforeSend: () => {
          loading && this.$f7.preloader.show()
        },
        success: (data, status, request) => {
          if (data.code === -1) {
            this.$f7.toast.show({ text: data.msg })
            this.$f7.views.main.router.navigate('/login', { reloadAll: true })
          } else {
            resolve(data)
          }
        },
        error: (xhr, status) => {
          this.$f7.toast.show({ text: '网络异常，请重试' })
        },
        complete: () => {
          loading && this.$f7.preloader.hide()
        }
      })
    })
  }
}